package com.xzzz.common.base.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 邮件处理工具类, 需要引入Jar包
 * <pre>
 * {@code
 * <dependency>
 *     <groupId>com.sun.mail</groupId>
 *     <artifactId>javax.mail</artifactId>
 *     <version>1.5.3</version>
 * </dependency>
 * }
 * </pre>
 *
 * @author xzzz
 */
public class MailUtil {
    private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**
     * 发送邮件方法
     *
     * @param title          发送邮件标题
     * @param msgs           发送邮件内容
     * @param sender         发送人的邮箱
     * @param senderPassWord 发送人邮箱的密钥
     * @param receiverArray  邮件接收人集合
     * @param mailHost       发送人的邮件服务器主机名
     * @return
     */
    public static boolean sendMail(String title, String msgs, String sender, String senderPassWord, Address[] receiverArray, String mailHost) {
        return sendMail(title, msgs, sender, senderPassWord, receiverArray, true, mailHost, "465", false);
    }

    /**
     * 发送邮件方法
     *
     * @param title          发送邮件标题
     * @param msgs           发送邮件内容
     * @param sender         发送人的邮箱
     * @param senderPassWord 发送人邮箱的密钥
     * @param receiverArray  邮件接收人集合
     * @param mailDebug      是否开启debug调试
     * @param mailHost       发送人的邮件服务器主机名
     * @param mailSmtpPort   发送人的邮件服务器端口
     * @param isHtml         邮件内容是否是html
     * @return
     */
    public static boolean sendMail(String title, String msgs, String sender, String senderPassWord, Address[] receiverArray, boolean mailDebug,
                                   String mailHost, String mailSmtpPort, boolean isHtml) {
        try {
            Properties props = new Properties();

            logger.info("发送邮件--start");

            // 开启debug调试
            props.setProperty("mail.debug", mailDebug + "");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.host", mailHost);
            // 设置邮件服务器端口默认"465"
            props.setProperty("mail.smtp.port", mailSmtpPort);
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            MailSSLSocketFactory sf = new MailSSLSocketFactory();

            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            Session session = Session.getInstance(props);

            Message msg = new MimeMessage(session);
            msg.setSubject(title);
            //设置邮件内容
            if (isHtml) {
                msg.setContent(msgs, "text/html;charset = utf-8");
            } else {
                msg.setText(msgs);
            }
            // 此处设置发件人邮箱
            msg.setFrom(new InternetAddress(sender));

            Transport transport = session.getTransport();
            // （邮件服务器主机名、发件人邮箱、发件人邮箱密码）
            transport.connect(mailHost, sender, senderPassWord);

            transport.sendMessage(msg, receiverArray);
            transport.close();
            logger.info("发送邮件--end");
            return true;

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            String title = "测试邮件";
            String resultMessage = "测试邮件内容内容内容";
            String sender = "666@qq.com";
            String senderPassWord = "PassWord";
            String mailHost = "smtp.qq.com";
            // 添加收件人地址 多个收件人存放list中
            List<Address> list = new ArrayList<Address>();
            list.add(new InternetAddress("13706618244@139.com"));
            Address[] senderList = list.toArray(new Address[list.size()]);
            MailUtil.sendMail(title, resultMessage, sender, senderPassWord, senderList, mailHost);
        } catch (AddressException e) {
            logger.error(e.getMessage(), e);
        }
    }

}
